package com.xzl.boilerplate.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xzl.boilerplate.common.dto.ResultResponse;
import com.xzl.boilerplate.common.dto.UserDTO;
import com.xzl.boilerplate.common.dto.exception.BizCode;
import com.xzl.boilerplate.common.dto.exception.BizException;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

public class RestTemplateUtil {
    RestTemplate restTemplate;
    public static ObjectMapper mapper = new ObjectMapper();


    public RestTemplateUtil(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public static ResultResponse getResultReponse(RestTemplate restTemplate, String url, HttpMethod httpMethod, Object body, String token) {
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + token);
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);

        String infra;
        try {
            infra = mapper.writeValueAsString(body);
        } catch (JsonProcessingException e) {
            throw new BizException(BizCode.JSON_CONVERT_ERROR);
        }
        HttpEntity<String> requestEntity = new HttpEntity<>(infra, headers);
        ResponseEntity<ResultResponse> result = restTemplate.exchange(url, httpMethod, requestEntity, ResultResponse.class, (Object) null);
        return result.getBody();
    }

    public <DATA> ResultResponse getBasePlatform(Class<DATA> clazz,String url, HttpMethod httpMethod, Object body, Map<String,String> headersMap) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type","application/json");
        if (headersMap != null && !headersMap.isEmpty()) {
            Iterator<String> iterator = headersMap.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                headers.add(key,headersMap.get(key));
            }
        }
        String infra = null;
        if (body!=null)
            infra = mapper.writeValueAsString(body);
        HttpEntity<String> requestEntity = new HttpEntity<>(infra, headers);

        ResponseEntity<Object> result = restTemplate.exchange(url, httpMethod, requestEntity, Object.class, (Object) null);
        String json = mapper.writeValueAsString(result.getBody());
//        ResultResponse<DATA> resultResponse = mapper.readValue(json, new TypeReference<ResultResponse<DATA>>(){});
        JavaType javaType = mapper.getTypeFactory().constructParametrizedType(ResultResponse.class, ResultResponse.class, clazz);
        ResultResponse<UserDTO> resultResponse = mapper.readValue(json, javaType);
        return resultResponse;
    }
}
